<template>
  <el-card class="home-card" shadow="hover">
    <div class="header">
      <h2>疫苗统计总览</h2>
      <el-radio-group v-model="timeRange" @change="handleTimeChange">
        <el-radio-button label="7days">近 7 日</el-radio-button>
        <el-radio-button label="30days">近 30 日</el-radio-button>
        <el-radio-button label="all">全部</el-radio-button>
      </el-radio-group>
    </div>

    <div class="charts">
      <div class="chart-item">
        <v-chart :option="overviewChart" autoresize @click="handleChartClick" />
      </div>
      <div class="chart-item">
        <v-chart :option="taskChart" autoresize @click="handleChartClick" />
      </div>
      <div class="chart-item">
        <v-chart :option="usageChart" autoresize />
      </div>
    </div>
  </el-card>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { use } from 'echarts/core'
import VChart from 'vue-echarts'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from 'echarts/components'

use([
  CanvasRenderer,
  PieChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
])

const router = useRouter()

// 筛选与分页
const timeRange = ref('7days')
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

const vaccines = ref([]) // 用于库存（这里示例为0）
const vaccineUsage = ref([]) // 接种数据
const checkTasks = ref([]) // 任务状态分布

const fetchData = async () => {
  try {
    const params = {
      timeRange: timeRange.value,
      search: searchKeyword.value.trim(),
      pageNum: currentPage.value,
      pageSize: pageSize.value,
    }

    const [overviewResp, taskResp, usageResp] = await Promise.all([
      axios.get('http://127.0.0.1:8181/api/statistics/vaccine-overview', {
        params,
      }),
      axios.get('http://127.0.0.1:8181/api/statistics/checktask-status', {
        params,
      }),
      axios.get('http://127.0.0.1:8181/api/statistics/vaccine-usage-ranking', {
        params,
      }),
    ])

    const overview = overviewResp.data.data || {}

    // vaccineUsage: [{ vaccine_name, quantity_used }]
    vaccineUsage.value = usageResp.data.data.map((item) => ({
      vaccine_name: item.vaccineName,
      quantity_used: item.totalUsed,
    }))

    // vaccines: 这里只是为了库存数，用 overview 接口结果替代
    vaccines.value = [
      {
        name: '全部疫苗',
        amount: overview.inventoryTotal || 0,
        numbering: '',
      },
    ]

    // 任务状态
    const statusMap = taskResp.data.data
    checkTasks.value = [
      { status: '未开始', count: statusMap['未开始'] || 0 },
      { status: '进行中', count: statusMap['进行中'] || 0 },
      { status: '已完成', count: statusMap['已完成'] || 0 },
    ]
  } catch (error) {
    console.error('数据获取失败', error)
    ElMessage.error('获取统计数据失败，请稍后再试')
  }
}

onMounted(fetchData)

watch([timeRange, searchKeyword, currentPage, pageSize], fetchData)

// 图表配置项
const overviewChart = computed(() => ({
  title: { text: '疫苗分布（库存/接种）', left: 'center' },
  tooltip: { trigger: 'item' },
  legend: { bottom: '0%', left: 'center' },
  series: [
    {
      type: 'pie',
      radius: '50%',
      name: '疫苗总览',
      data: [
        {
          value: vaccines.value.reduce((sum, v) => sum + v.amount, 0),
          name: '库存总数',
        },
        {
          value: vaccineUsage.value.reduce(
            (sum, v) => sum + v.quantity_used,
            0
          ),
          name: '接种总数',
        },
      ],
    },
  ],
}))

const taskChart = computed(() => ({
  title: { text: '核查任务状态分布', left: 'center' },
  tooltip: { trigger: 'item' },
  legend: { bottom: '0%', left: 'center' },
  series: [
    {
      type: 'pie',
      radius: '50%',
      name: '任务状态',
      data: checkTasks.value.map((item) => ({
        name: item.status,
        value: item.count,
      })),
    },
  ],
}))

const usageChart = computed(() => ({
  title: { text: '疫苗接种量排行', left: 'center' },
  tooltip: { trigger: 'axis' },
  xAxis: {
    type: 'category',
    data: vaccineUsage.value.map((v) => v.vaccine_name),
  },
  yAxis: { type: 'value' },
  series: [
    {
      type: 'bar',
      name: '接种数量',
      data: vaccineUsage.value.map((v) => v.quantity_used),
      itemStyle: { color: '#67C23A' },
    },
  ],
}))

// 点击图表跳转
function handleChartClick(params) {
  if (params.name.includes('任务')) {
    router.push({ name: 'CheckTaskPage' })
  } else if (params.name.includes('接种')) {
    router.push({ name: 'VaccineUsagePage' })
  }
}

function handleTimeChange() {
  // 自动触发 fetchData，已通过 watch 实现
}
</script>

<style scoped>
.home-card {
  padding: 20px;
  margin: 20px;
}
.header {
  text-align: center;
  margin-bottom: 20px;
}
.charts {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 20px;
}
.chart-item {
  flex: 0 0 30%;
  min-width: 300px;
  height: 300px;
}
@media (max-width: 992px) {
  .chart-item {
    flex: 0 0 45%;
  }
}
@media (max-width: 600px) {
  .chart-item {
    flex: 0 0 100%;
  }
}
</style>
